<template>
    <h4>============远程m32控制台=================
    <button @click="sock_go()">{{stas}}</button></h4>
   <!-- 代理服务端地址：<input type="text" v-model="remote_host" ref="my_input"> -->

    <div class="kuang" id="xxx2">
        <div v-for="content in cmdStore.all_cmds">
            <SmartPre class="display_sp" :txt="content" />
        </div>
        <!-- <li v-for="msg in bootloader_msg" class="tip-msg">{{msg}}</li> -->
        <p class="display_sp">{{sstr}}</p>
    </div>
    <br>
   <!-- <button @click="do_app_upgrade()">升级APP</button> -->

</template>

<script setup>
    import Mousetrap from 'mousetrap' //处理快捷键的库
    import { onMounted,onUnmounted,ref,computed,nextTick,
            reactive,inject,onActivated,onDeactivated } from 'vue'
    import SmartPre from '/src/components/SmartPre.vue'
    import {  useCmdStore } from '../store/cmds.js'
    // import {  decode } from 'web-iconv'
    import axios from 'axios'

    const my_input = ref()
    const sstr = ref('')
    const stas = ref('连接')
    const remote_host = inject('serve_addr') //ref('rqd-ThinkPad-T450')

    const cmdStore = useCmdStore()

    let g_ws = null
    let wait_res = null

    function process_msg(msg){
        const div = document.getElementById('xxx2')
        const ww = new TextDecoder('gbk')
        const text = ww.decode(msg)
        // if(wait_res == '2'){
        //     sstr.value = text
        //     wait_res = null
        //     return
        // }
        // if(wait_res == '1'){
        //     console.log(text)
        //     sstr.value = text.substring(7)
        //     wait_res = null
        //     return
        // }
        cmdStore.push(text)

        nextTick(() => {
            div ? div.scrollTop = div.scrollHeight : 1+1
        })

    }

    onMounted(() => {
        document.addEventListener('keypress', handleKeyboardEvt)
        Mousetrap.bind(['del', 'backspace'], function() {
            sstr.value = sstr.value.substr(0, sstr.value.length-1)
        })

        Mousetrap.bind('ctrl+/', function() { //模拟Tab键输入
                const ss = sstr.value
                const data = stringToUint8Array_apx(ss,9)

                if (g_ws && g_ws.readyState == 1) {
                    g_ws.send(data)
                    sstr.value = ""
                } else {
                    sstr.value = "     ---not connected---"
                    return
                }
                wait_res = '1'
        })

    })
    onUnmounted(() => {
        document.removeEventListener('keypress', handleKeyboardEvt)
        if(g_ws) g_ws.close()

    })
    onActivated(()=>{
        const div = document.getElementById('xxx2')
        div.scrollTop = div.scrollHeight
        document.addEventListener('keypress', handleKeyboardEvt)

    })
    onDeactivated(()=>{
        document.removeEventListener('keypress', handleKeyboardEvt)
    })
    function sock_go() {
        const ws = new WebSocket('ws://' + remote_host.value + ':10088/m32_cmd/')
        ws.onmessage = (evt) => {
            const reader = new FileReader()
            reader.onload = (e) => {
                const res = reader.result
                process_msg(new Uint8Array(res))
            }
            reader.readAsArrayBuffer(evt.data)

        }

        ws.onopen = (evt) => {
            stas.value = '已连接!'
            if (g_ws) {
                g_ws.close()
                g_ws = null
            }
            g_ws = ws
        }

    }


    function handleKeyboardEvt(e) {
        //console.log(e)
        if (e.target == my_input.value) return

        var key = window.event ? e.keyCode : e.which;
        if (key == 13 || key == 10) {
            //sstr.value += String.fromCharCode(key)
            if (sstr.value == 'clear') {
                cmdStore.$reset()
                sstr.value = ''
                return
            }

            if (g_ws && g_ws.readyState == 1) {
                g_ws.send(sstr.value)
                g_ws.send('\n')
                sstr.value = ""
                return
            } else {
                sstr.value = "     ---not connected---"
                return
            }

        }
        sstr.value += String.fromCharCode(key)
    }

    // function do_button_click() {
    //     if (stas.value == 'Go') {
    //         sock_go()
    //     } else {
    //         console.log('====连接的时机未成熟===')
    //     }
    // }

    function stringToUint8Array_apx(str,ap_num){
        var arr = [];
        for (var i = 0, j = str.length; i < j; ++i) {
            arr.push(str.charCodeAt(i));
        }
        arr.push(ap_num)

        var tmpUint8Array = new Uint8Array(arr);
        return tmpUint8Array
    }


    function test_send_cmd(num) {
        if (1 == num) {
            axios({
                method: 'get',
                url: '/api/m32_cmd?aa=123&bb=hello',
                data: {
                    cc: '哈哈哈',
                    dd: new Date()
                }
            }).then(res => {
                console.log("py-web回复来了", res)
            })
        }

        if (0 == num) {
            axios({
                method: 'get',
                url: 'http://rqd-ThinkPad-T450:8088/m32_cmd?aa=999&bb=world',
                data: {
                    cc: '哈哈哈',
                    dd: new Date()
                }
            }).then(res => {
                console.log("2py-web回复来了", res)
            })
        }
    }

    let  orig_func = null
    let  num = 0
    let  int_tim = null

    // function do_app_upgrade(){
    //     if(sstr.value.trim()==""){
    //         sstr.value="    ----在此处输入待升级的App文件路径----"
    //         return
    //     }
    //     let bin_data=null
    //     try{
    //         bin_data = window.rrapi.readFileSync(sstr.value.trim())
    //     }catch(e){
    //         sstr.value = "    ---读文件出错--"
    //         return
    //     }

    //     if(g_ws && g_ws.readyState==1){
    //         g_ws.send('ggo 2\n')
    //         orig_func = g_ws.onmessage
    //         g_ws.onmessage = (evt)=>{
    //             const reader = new FileReader()
    //             reader.onload = (e) => {
    //                 const res = reader.result
    //                 const data = new Uint8Array(res)
    //                 const decoder = new TextDecoder('gbk')
    //                 const text = decoder.decode(data)
    //                 //bootloader_msg.push(text)
    //                 cmdStore.push("<<>>" + text)
    //                 nextTick(() => {
    //                     const div = document.getElementById("xxx2")
    //                     div.scrollTop = div.scrollHeight
    //                 })

    //                 if(text.match("等待升级") && (++num == 3)){
    //                     sstr.value = "[正在升级]"
    //                     g_ws.send(bin_data)
    //                     setTimeout(()=>{
    //                         g_ws.send('App_send_finish\n')
    //                     },900)


    //                     setTimeout(()=>{
    //                         g_ws.onmessage = orig_func
    //                         sstr.value=""
    //                         clearInterval(int_tim)
    //                     },9200)
    //                     int_tim = setInterval(()=>{
    //                         sstr.value +="#"
    //                     },400)
    //                 }
    //             }
    //             reader.readAsArrayBuffer(evt.data)
    //         }
    //     }else{
    //         sstr.value="     ---not connected---"
    //     }
    // }
</script>

<style scoped>
    .display_sp {
        white-space: pre;
        text-align: left;
        tab-size: 8;
        margin: 0;
        font-size: 1.2em;
    }

    p::before {
        content: ">>>";
        color: #cdcd22;
    }

    p {
        text-align: left;
        font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
        /*     border: 2px solid papayawhip;
        border-top: none; */
    }

    p::after {
        content: "▌";
        color: #56ff23;
    }

    input {
        font-size: 1.1em;
        width: 22em;
    }

    button {
       /*   color: darkgrey;
        background-color: #565656;
       height: 1.2em; */
        margin-left: 0.4em;
        padding: 0.2em 1em;
    }

    .kuang {
        max-height: 32em;
        min-height: 1em;
        overflow-y: scroll;
        border: 2px solid papayawhip;
        padding: 0 0.6em;
        /* border-bottom: none; */
    }

@media (prefers-color-scheme: light) {
    .kuang{
        border: 2px solid darkblue;
    }
    p::before {
        content: ">>>";
        color: #23ed22;
    }
}
</style>
